<!DOCTYPE html>
<html>

<head>
    <title>
        WebSocket演示
    </title>

</head>

<body>

    <div>
        <div id="divMsg" style="background-color:whitesmoke">

        </div>
        <div>
            <input type="text" id="txtMsg" placeholder="输入要发送的内容"><button name="btnSend" id="btnSend">发送</button>
        </div>
    </div>

    <script>
        var txtMsg = document.getElementById('txtMsg')
        var btnSend = document.getElementById('btnSend')
        var divMsg = document.getElementById('divMsg')

        var webSocket = new WebSocket('ws://127.0.0.1:8081/websocket')

        webSocket.addEventListener("open", function () {
            divMsg.innerHTML = divMsg.innerHTML + "<div>连接成功！</div>"
        })

        webSocket.addEventListener("message", function (e) {
            divMsg.innerHTML = divMsg.innerHTML + "<div>Server:" + e.data + "</div>"
        })

        btnSend.addEventListener("click", function () {
            var msg = txtMsg.value

            webSocket.send(msg)
        })
    </script>
</body>

</html>